import request from '../utils/request'

// 简单聊天
export const simpleChat = (params) => request.get('/chat-client/simple/chat', {params});

// 流式API聊天
export const fluxChat = (params) => request.get('/chat-client/stream/chat', {params});


// 获取单次对话的详细内容 , 需要提供对话ID
export const getChatRecords = (params) => request.get('/chat-client/records', {params});


// 根据用户id , 获取历史对话记录列表
export const getChatHistory = (params) => request.get('/chat-client/history', {params});


// 流式聊天 - 使用Server-Sent Events
export const streamChat = async (params, onMessage, onComplete, onError) => {
    try {
        const url = new URL('/api/chat-client/stream/chat', window.location.origin);
        // 添加查询参数
        Object.keys(params).forEach(key => {
            url.searchParams.append(key, params[key]);
        });

        const eventSource = new EventSource(url.toString());

        eventSource.onmessage = (event) => {
            if (event.data) {
                onMessage && onMessage(event.data);
            }
        };

        eventSource.onerror = (error) => {
            console.error('Stream error:', error);
            eventSource.close();
            onError && onError(error);
        };

        eventSource.addEventListener('end', () => {
            eventSource.close();
            onComplete && onComplete();
        });

        return eventSource;
    } catch (error) {
        console.error('Stream connection error:', error);
        onError && onError(error);
    }
};

// 使用fetch实现流式读取的替代方案
export const streamChatFetch = async (params, onMessage, onComplete, onError) => {
    try {
        const url = new URL('/api/chat-client/stream/chat', window.location.origin);
        Object.keys(params).forEach(key => {
            url.searchParams.append(key, params[key]);
        });

        const response = await fetch(url.toString(), {
            method: 'GET',
            headers: {
                'Accept': 'text/plain',
                'Cache-Control': 'no-cache'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        let buffer = '';

        while (true) {
            const {done, value} = await reader.read();

            if (done) {
                // 处理剩余的buffer内容
                if (buffer.trim()) {
                    onMessage && onMessage(buffer);
                }
                onComplete && onComplete();
                break;
            }

            // 将新的数据添加到buffer
            const chunk = decoder.decode(value, {stream: true});
            buffer += chunk;

            // 由于Spring WebFlux返回的是连续的字符串流，我们直接传递每个chunk
            // 如果后端返回的是按行分割的数据，取消下面的注释，使用按行处理
            if (chunk.trim()) {
                onMessage && onMessage(chunk);
            }

            // 如果需要按行处理，使用下面的代码替换上面的直接处理
            /*
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留最后一个不完整的行

            // 处理完整的行
            for (const line of lines) {
              if (line.trim()) {
                onMessage && onMessage(line);
              }
            }
            */
        }
    } catch (error) {
        console.error('Stream fetch error:', error);
        onError && onError(error);
    }
};


